import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'
Vue.use(Router)
import store from "@/store";

// 解决NavigationDuplicated问题 --开始
//这个问题对于程序本身没有任何影响，但是重复的冗余导航会导致报错，这个我们使用promise的失败的回调函数捕捉一下就可以了(把错误吞了)，不管也没事
let originPush = Router.prototype.push
let originReplace = Router.prototype.replace

Router.prototype.push = function (location, resolve, reject) {
  // console.log(this);//这个this指的是Router，push函数本身需要 this指向Router
  if (resolve && reject) {
    originPush.call(this, location, resolve, reject)
  } else {
    originPush.call(this, location, () => { }, () => { })
  }

}
Router.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject)
  } else {
    originReplace.call(this, location, () => { }, (err) => { })
  }
}
// 解决NavigationDuplicated问题--结束

let router = new Router({
  routes,
  scrollBehavior(to, from, savedPosition) {
    return { y: 0 }//返回y=0表示，滚动条在最上方
  }
})

router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token
  let name = store.state.user.userInfo.name
  if (token) {
    if (to.path == '/login' || to.path == '/register') {
      next('/')//已经登录了，放行到首页,放行
    } else {
      //已经登录，访问非登录与注册
      if (name) {
        next()//放行
      } else {
        try {
          await store.dispatch('user/getUserInfo')//应为只在home组件，派发了请求获取用户信息，当我们在search组件刷新时，会丢失用户信息，这里需要重新派发
          next()
        } catch (error) {
          //token失效，重新登录
          await store.dispatch('user/Logout')
          next('/login')
        }
      }
    }
  } else {
    //用户未登录
    if (to.path.indexOf("/trade") != -1 || to.path.indexOf('/pay') != -1 || to.path.indexOf('/center') != -1) {
      next('/login?redirect=' + to.path)
    } else {
      next()
    }


  }
})
export default router;